package com.xmotor.test_annotation_StrategyModel.service;

import com.alibaba.fastjson.JSON;
import com.xmotor.test_annotation_StrategyModel.annotation.OrderHandlerType;
import com.xmotor.test_annotation_StrategyModel.handler.OrderHandler;
import com.xmotor.test_annotation_StrategyModel.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author Dang Xianyue
 * @Date 2020-10-05 16:10
 * @Version 1.0
 */
@Service(value = "test_annotation_StrategyModel_orderService")
public class OrderService {

    private Map<String, OrderHandler> orderHandleMap = new HashMap<>(32);

    @Autowired
    public void setOrderHandleMap(List<OrderHandler> orderHandlers) {
        // 注入各种类型的订单处理类
        if (orderHandlers != null && orderHandlers.size() > 0){
            for (OrderHandler orderHandler : orderHandlers) {
                OrderHandlerType annotation = AnnotationUtils.findAnnotation(orderHandler.getClass(), OrderHandlerType.class);
                if (annotation != null){
                    String[] sourceArr = annotation.source();
                    String[] payMethodArr = annotation.payMethod();
                    if (payMethodArr != null && payMethodArr.length > 0){
                        //key为来源+支付方式（如：mobile_AliPay）
                        for (int i = 0; i < sourceArr.length; i++) {
                            for (int j = 0; j < payMethodArr.length; j++) {
                                orderHandleMap.put(sourceArr[i] + "_" + payMethodArr[j],orderHandler);
                            }
                        }
                    }else {
                        for (int i = 0; i < sourceArr.length; i++) {
                            orderHandleMap.put(sourceArr[i],orderHandler);
                        }
                    }
                }

            }
            System.out.println(JSON.toJSONString(orderHandleMap));
        }
    }

    public String orderService(Order order) {
//        if(order.getSource().equals("pc")){
//            // 处理pc端订单的逻辑
//        }else if(order.getSource().equals("mobile")){
//            // 处理移动端订单的逻辑
//        }else {
//            // 其他逻辑
//        }

        // ...一些前置处理

        // 通过订单来源确定对应的handler

        OrderHandler orderHandler = orderHandleMap.get(order.getSource() + "_" + order.getPayMethod());
        if (orderHandler == null){
            orderHandler = orderHandleMap.get(order.getSource());
            if (orderHandler == null){
                orderHandler = orderHandleMap.get("default");
            }
        }
        String handleMsg = orderHandler.handle(order);
        System.out.println("订单处理日志：" + handleMsg);

        // ...一些后置处理
        return handleMsg;
    }
}
